#!/usr/bin/python3
# encoding: utf-8

import logging
from logging import handlers
import os

# set logger
logger = logging.getLogger("kill.log")
logger.setLevel(logging.INFO)
format_str = logging.Formatter('%(asctime)-15s %(message)s')  # 设置日志格式
time_handler = handlers.TimedRotatingFileHandler(filename="kill.log", when='D', backupCount=4, encoding="utf-8")
time_handler.setFormatter(format_str)
logger.addHandler(time_handler)


def get_memory_info():
    import psutil
    # 获取系统总内存和可用内存
    mem = psutil.virtual_memory()
    total_memory = mem.total / (1024 ** 3)  # 转换为GB
    available_memory = mem.available / (1024 ** 3)  # 转换为GB
    used_memory = mem.used / (1024 ** 3)  # 转换为GB
    logger.info(f"总内存: {total_memory:.2f} GB, 可用内存: {available_memory:.2f} GB, 已用内存: {used_memory:.2f} GB")


def get_top_processes(n=5):
    import psutil
    # 获取并排序所有进程，按内存使用量
    processes = [(p.pid, p.info['name'], p.info['memory_info'].rss / (1024 ** 2)) 
                 for p in psutil.process_iter(['name', 'memory_info'])]

    # 根据内存使用量排序（降序）
    top_processes = sorted(processes, key=lambda x: x[2], reverse=True)[:n]

    logger.info(f"占用内存最高的{len(top_processes)}个进程:")
    for pid, name, memory in top_processes:
        logger.info(f"进程ID: {pid}, 进程名: {name}, 内存使用: {memory:.2f} MB")


if __name__ == "__main__":
    kill_info = {
        "description": "kill process " + os.getenv("EARLYOOM_NAME"),
        "PID": os.getenv("EARLYOOM_PID"), "UID": os.getenv("EARLYOOM_UID"),
        "CMDLINE": os.getenv("EARLYOOM_CMDLINE", "No cmdline").rstrip(),
        "RSS":  "{} MB".format(os.getenv("EARLYOOM_VM_RSS_MB"))
    }
    logger.warning(kill_info)
    # get_memory_info()
    # get_top_processes()
